from peewee import *
from api.utils import get_uuid
from datetime import datetime
from api.db.db_models import DB, DataBaseModel

class Track(DataBaseModel):
    id = CharField(primary_key=True)
    anonymous_user_id = CharField(null=True, index=True)
    login_user_email = CharField(null=True, index=True)
    conversation_id=CharField(null=True, index=True)
    question = TextField(null=False)
    answer = TextField(null=True)
    timestamp = DateTimeField(null=False, index=True)

    class Meta:
        db_table = 'user_questions'

class TrackService:
    @classmethod
    @DB.connection_context()
    def save_question(cls, anonymous_user_id=None, login_user_email=None, question=None, timestamp=None, conversation_id=None):
        """保存用户问题到数据库"""
        if not timestamp:
            timestamp = datetime.now()
        
        track = {
            "id": get_uuid(),
            "anonymous_user_id": anonymous_user_id,
            "login_user_email": login_user_email,  # 改为邮箱字段
            "conversation_id":conversation_id,
            "question": question,
            "timestamp": timestamp
        }
        return Track.create(**track)

    @classmethod
    @DB.connection_context()
    def update_answer(cls, question_id, answer):
        """更新机器人回答"""
        return Track.update(answer=answer).where(Track.id == question_id).execute()

    @classmethod
    def get_questions(cls, anonymous_user_id=None, login_user_email=None, 
                    start_timestamp=None, end_timestamp=None):
        """获取问题记录（统一使用update_time时间戳）"""
        query = Track.select()
        
        if anonymous_user_id:
            query = query.where(Track.anonymous_user_id == anonymous_user_id)
        if login_user_email:
            query = query.where(Track.login_user_email == login_user_email)
        
        # 使用时间戳过滤
        if start_timestamp is not None:
            query = query.where(Track.update_time >= start_timestamp)
        if end_timestamp is not None:
            query = query.where(Track.update_time <= end_timestamp)
        
        return query.order_by(Track.update_time.desc())